﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using CommDll;
using DevComponents.DotNetBar.Controls;

namespace HospitalMedicineTraceability
{
    /// <summary>
    /// ClassName:frmQuery_CollectPharmacyStockOut
    /// Version:1.0
    /// Date:2024-07-08
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为药房出库采集电监码查询
    /// </remarks>
    public partial class frmQuery_CollectPharmacyStockOut : DevComponents.DotNetBar.OfficeForm
    {
        #region 01.自定义属性
        public int m_nKind;  // 0:查询 1:核对
        public DataTable m_dt;  // 保存查询出来的数据
        private string m_strWhere = "";  // 固定条件
        private int m_nRowsIndex0 = -1; // 明细单用
        private Timer m_timerShowData = new Timer(); // 延时显示数据
        #endregion
        public frmQuery_CollectPharmacyStockOut()
        {
            InitializeComponent();
            m_timerShowData.Enabled = true;
            m_timerShowData.Interval = 10;
            m_timerShowData.Tick += new System.EventHandler(timerShowData_Tick);
        }
        #region 02.自定义方法

        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strFieldName = "", strFieldSql = "", strFieldWidth = "";
            // 1 主数据表格
            string strDgvName = this.Name + "_01";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值 
            strFieldName = "Id-序号,Code-出库单号,PharmacyCode-药房编号,PharmacyName-药房名称,StockOutTime-出库时间,BillAmount-明细数量,GoodsAmount-商品数量,SupervisionCodeCollectAmount-商品数量_采集,SupervisionCodeCollectCount-电监码条数_采集,SupervisionCodeCollectStatus-采码状态,SupervisionCodeCollectTime-采码时间,SupervisionCodeCollectName-采码人,PatientIdCode-患者证件号,PatientName-患者名称";
            strFieldSql = "Id,Code,PharmacyCode,PharmacyName,PatientIdCode,PatientName,StockOutTime,BillAmount,GoodsAmount,SupervisionCodeCollectAmount,SupervisionCodeCollectCount,SupervisionCodeCollectStatus,SupervisionCodeCollectTime,SupervisionCodeCollectName"; 
            strFieldWidth = "0,120";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);            
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);            
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvMain.Tag = strDgvName;
            this.dgvMain.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvMain.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvMain.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色

            // 2 明细数据表格
            strDgvName = this.Name + "_02";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strDgvName))
            {
                AppConfig._initDictField(strDgvName);
                //return;
            }
            // 默认值
            strFieldName = "Code-药品编号,Name-药品名称,PackageSpec-规格,Unit-单位,Manufacturer-生产厂家,MakeDate-生产日期,ExpiredDate-有效期,Money-金额,Amount-商品数量,SupervisionCodeCollectAmount-商品数量_采集,SupervisionCodeCollectCount-电监码条数_采集,SupervisionCodeCollectStatus-采码状态,SupervisionCodeCollectTime-采码时间,SupervisionCodeCollectMethod-采码方式";
            strFieldSql = "Code,Name,PackageSpec,Unit,Manufacturer,MakeDate,ExpiredDate,Money,Amount,SupervisionCodeCollectAmount,SupervisionCodeCollectCount,SupervisionCodeCollectStatus,SupervisionCodeCollectTime,SupervisionCodeCollectMethod";
            strFieldWidth = "100,140,120,80,200,120";
            AppConfig.m_dictFieldName.Add(strDgvName, strFieldName);
            AppConfig.m_dictFieldSql.Add(strDgvName, strFieldSql);
            AppConfig.m_dictField0.Add(strDgvName, strFieldSql);
            AppConfig.m_dictFieldWidth0.Add(strDgvName, strFieldWidth);
            // 设置值
            strFieldSql = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strDgvName), AppConfig.m_dictField0[strDgvName]).Trim();
            AppConfig.m_dictField.Add(strDgvName, strFieldSql);
            strFieldWidth = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strDgvName), AppConfig.m_dictFieldWidth0[strDgvName]).Trim();
            AppConfig.m_dictFieldWidth.Add(strDgvName, strFieldWidth);
            // 02 右键双击设置显示方式
            this.dgvDetail.Tag = strDgvName;
            this.dgvDetail.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(DataDeal.dataGridView_MouseDoubleClick);
            // 03 其他事件
            this.dgvDetail.ColumnHeaderMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(CommFun._dgvColumnHeaderSort);// 排序
            this.dgvDetail.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(CommFun._dgvRowEnter);// 改变行颜色
        }

        private void timerShowData_Tick(object sender, EventArgs e)
        {
            m_timerShowData.Enabled = false;
            _initPharmacy();
        }

        /// <summary>
        /// 初始化药房信息信息
        /// </summary>
        private void _initPharmacy()
        {
            string strSql = "";
            // 药房信息
            strSql = "select PharmacyCode + '|' + PharmacyName as Supplier from TH_PharmacyStockOut group by PharmacyCode,PharmacyName";
            DataTable dt = AppInfo._openSql_DataTable(strSql);
            if (dt != null && dt.Rows.Count > 0)
            {
                FunctionComm._setInfoToCbb_Dt(cbbPharmacy, dt);
            }
            cbbPharmacy.DrawItem += new System.Windows.Forms.DrawItemEventHandler(CommFun._cbbDrawItem);
            //状态信息
            cbbStatus.DrawItem += new System.Windows.Forms.DrawItemEventHandler(CommFun._cbbDrawItem);
            // 
            btnNew.Visible = (m_nKind == 1);
            btnExport.Top = (m_nKind == 0) ? btnNew.Top : btnExport.Top; 
            //
            cbDate.Checked = true;
            _query();
        }      

        /// <summary>
        /// 取查询条件
        /// </summary>
        private Boolean _getQueryWhere(ref string strWhere)
        {
            Boolean bResult = false;
            string strTemp = "";
            // 00 取配企信息
            if (cbPharmacy.Checked && cbbPharmacy.SelectedIndex > -1)
            {
                strTemp = cbbPharmacy.Text.Split('|')[0].Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(PharmacyCode = '{0}')", strTemp);
                }
            }
            // 00 取采码状态
            if (cbStatus.Checked && cbbStatus.SelectedIndex > -1)
            {
                strTemp = cbbStatus.Text.Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(case when isnull(SupervisionCodeCollectStatus,'') = '' then '未采' else SupervisionCodeCollectStatus end = '{0}')", strTemp);
                }
            }

            // 00 取患者信息
            if (cbPatient.Checked)
            {
                strTemp = txtPatient.Text.Trim();
                if (!strTemp.Equals(""))
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(PatientIdCode like '%{0}%' or PatientName like '%{0}%')", strTemp);
                }
            }

            // 02 取发票日期
            if (cbDate.Checked)
            {
                if (dtpDateBegin.Value.ToString("yyyy-MM").CompareTo(dtpDateEnd.Value.ToString("yyyy-MM")) > 0)
                {
                    CommFun._messageBoxShow(string.Format("起始年月大于终止年月！"), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return bResult;
                }
                else
                {
                    strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(StockOutTime between '{0}' and '{1}')", dtpDateBegin.Value.ToString("yyyy-MM-dd"), dtpDateEnd.Value.AddDays(1).ToString("yyyy-MM-dd"));
                }
            }           

            bResult = true;
            return bResult;
        }

        /// <summary>
        /// 取查询条件(复核人等)
        /// </summary>
        private Boolean _getQueryWhere1(ref string strWhere)
        {
            Boolean bResult = false;
            //string strTemp = "";
            //// 发票类别
            //if (cbInvoiceKind.Checked && cbbInvoiceKind.SelectedIndex > -1)
            //{
            //    strTemp = cbbInvoiceKind.Text.Split('|')[0].Trim();
            //    if (!strTemp.Equals(""))
            //    {
            //        strWhere += (strWhere.Equals("") ? "" : " and ") + string.Format("(InvoiceKind = '{0}')", strTemp);
            //    }
            //}
            bResult = true;
            return bResult;
        }

        /// <summary>
        /// 信息查询
        /// </summary>
        private void _query()
        {
            if (m_dt != null)
            {
                m_dt.Dispose();
            }
            // 00 取条件:有参数时按参数来取数据
            string strWhere = m_strWhere;
            string strWhere1 = "";
            if (_getQueryWhere(ref strWhere))
            {
                if (!strWhere.Equals(""))
                {
                    strWhere = string.Format(" and {0}", strWhere);
                }
                // 取配送人条件
                _getQueryWhere1(ref strWhere1);
                if (!strWhere1.Equals(""))
                {
                    strWhere1 = string.Format(" and {0}", strWhere1);
                }
                // 02 取数据
                string strSql = string.Format(@"
                    select {0} from
                    (
                       select * from TH_PharmacyStockOut where 1=1
                       {{0}}
                    )A where 1=1 {{1}} order by StockOutTime Desc
                "
                , AppConfig.m_dictFieldSql[dgvMain.Tag.ToString()]);                
                strSql = string.Format(strSql, strWhere, strWhere1);
                m_dt = AppInfo._openSql_DataTable(strSql);
            }
            // 03 显示数据
            DataTable dt = null;
            if (m_dt != null)
            {
                dt = m_dt.Copy();
            }
            _showData(dt);
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showData(DataTable dt)
        {
            m_nRowsIndex0 = -1;
            if (dgvDetail.Rows.Count > 0)
            {
                ((DataTable)dgvDetail.DataSource).Rows.Clear();                
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                // 0101 调整字段顺序
                CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvMain.Tag.ToString()]);
                // 0102 显示数据
                CommFun._showDataGridView(dgvMain, dt, AppConfig.m_dictFieldWidth[dgvMain.Tag.ToString()], AppConfig.m_dictFieldName[dgvMain.Tag.ToString()]);
            }
            else {
                // 清除数据
                DataTable dtTemp = (DataTable)dgvMain.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }      
            }
            gbMain.Text = string.Format("出库信息【记录数:{0}】", dgvMain.Rows.Count);
            _showStatus("Main");
        }

        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="dt"></param>
        private void _showDetail()
        {
            // 00 清除数据
            if (dgvDetail.Rows.Count > 0)
            {
                DataTable dtTemp = (DataTable)dgvDetail.DataSource;
                if (dtTemp != null && dtTemp.Rows.Count > 0)
                {
                    dtTemp.Rows.Clear();
                }
            }
            // 01 按编号取数据
            if (m_nRowsIndex0 >= 0)
            {
                string strStockOut_Code = "";
                string strSupplierCode = "";
                strStockOut_Code = dgvMain.Rows[m_nRowsIndex0].Cells["Code"].Value.ToString();
                strSupplierCode = dgvMain.Rows[m_nRowsIndex0].Cells["PharmacyCode"].Value.ToString();
                try
                {
                    string strSql = @"select {0} from 
                     (
                        select * from TH_PharmacyStockOutDetail where PharmacyCode = '{1}' and StockOut_Code = '{2}'
                     )A order by Id";
                    strSql = string.Format(strSql, AppConfig.m_dictFieldSql[dgvDetail.Tag.ToString()], strSupplierCode, strStockOut_Code);
                    DataTable dt = AppInfo._openSql_DataTable(strSql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        // 0101 调整字段顺序
                        CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[dgvDetail.Tag.ToString()]);
                        // 0102 显示数据
                        CommFun._showDataGridView(dgvDetail, dt, AppConfig.m_dictFieldWidth[dgvDetail.Tag.ToString()], AppConfig.m_dictFieldName[dgvDetail.Tag.ToString()]);
                    }
                }
                catch (Exception ex)
                {
                    CommFun._messageBoxShow(ex.Message);
                    return;
                }
            }
            gbDetail.Text = string.Format("出库明细信息【记录数:{0}】", dgvDetail.Rows.Count);
            _showStatus("Detail");
        }

        /// <summary>
        /// 显示状态
        /// </summary>
        private void _showStatus(string strKind = "Main")
        {
            string strStatus = "";
            // 更新颜色
            if (strKind == "Main")
            {
                foreach (DataGridViewRow dr in dgvMain.Rows)
                {
                    strStatus = dr.Cells["SupervisionCodeCollectStatus"].Value.ToString();
                    if (strStatus != "全采")
                    {
                        //dr.DefaultCellStyle.BackColor = Color.LightSteelBlue;
                        dr.DefaultCellStyle.ForeColor = Color.Red;
                    }
                    else
                    {
                        //dr.DefaultCellStyle.BackColor = Color.White;
                        dr.DefaultCellStyle.ForeColor = Color.Black;
                    }
                }
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void _init()
        {
            // 01 dataGridViewX1设为不可编辑
            dgvMain.ReadOnly = true;
            //dgvMain.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            // 02 初始化日期
            dtpDateBegin.Format = DateTimePickerFormat.Custom;
            dtpDateBegin.CustomFormat = "yyyy-MM-dd";
            dtpDateEnd.Format = dtpDateBegin.Format;
            dtpDateEnd.CustomFormat = dtpDateBegin.CustomFormat;
            dtpDateEnd.Value = DateTime.Now;
            dtpDateBegin.Value = dtpDateEnd.Value;
            //dtpDateBegin.Value = dtpDateEnd.Value.AddDays(AppConfig.m_nDateBeforeStockIn * -1);
            // 03 初始化DataGridView
            _initDgvTitle();
            
            // 06 splitContainer1
            dgvMain.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top
                    | System.Windows.Forms.AnchorStyles.Right | System.Windows.Forms.AnchorStyles.Bottom));
            splitContainer1.Tag = this.Name + "_splitContainerHeight";
            splitContainer1.SplitterDistance = FunctionComm._strToInt(AppConfig.m_iniSetup._readValue("Common", splitContainer1.Tag.ToString(), splitContainer1.SplitterDistance.ToString()).Trim(), splitContainer1.SplitterDistance);
            splitContainer1.SplitterMoved += DataDeal.splitContainer_SplitterMoved;
        }
        #endregion

        #region 03.系统事件方法

        private void frm_Load(object sender, EventArgs e)
        {
            _init();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            // 数据查询
            _query();           
        }
        #endregion

        #region GridViewX事件
        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender,e);
            // 显示明细
            if (!(e.RowIndex < 0 || e.ColumnIndex < 0))
            {
                if (m_nRowsIndex0 != e.RowIndex)
                {
                    m_nRowsIndex0 = e.RowIndex;
                    _showDetail();
                }
            } 
        }

        #endregion

        private void dgvMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                e.Handled = true;
            }               
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (dgvMain != null && dgvMain.Rows.Count > 0)
            {
                CommFun._ExportExcel("", dgvMain);
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            //扫码入库(需先进行扫码配企确定)
            frmCollectPharmacyStockOut_Bat frm = new frmCollectPharmacyStockOut_Bat();
            frm.ShowDialog();
            if (frm.m_bIsRefresh)
            {
                btnQuery_Click(null,null);
            }
        }

        private void dgvMain_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (!(e.RowIndex < 0 || e.ColumnIndex < 0))
            {
                //扫码退库(需先进行扫码确定退库单)
                if (!dgvMain.CurrentRow.Cells["SupervisionCodeCollectStatus"].Value.ToString().Equals("全采"))
                {
                    frmCollectPharmacyStockOut_Bat frm = new frmCollectPharmacyStockOut_Bat();
                    frm.m_dictInfo.Add("BillCode", dgvMain.CurrentRow.Cells["Code"].Value.ToString());
                    frm.ShowDialog();
                    if (frm.m_bIsRefresh)
                    {
                        btnQuery_Click(null, null);
                    }
                }
            }
        }
    }
}